<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="consultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="咨询列表ID" align="center" prop="id"/>
      <el-table-column label="标题" align="center" prop="title"/>
      <!--      <el-table-column label="内容" align="center" prop="content" />-->
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="病种" align="center" prop="illnessName">
        <!--        <template slot-scope="scope">-->
        <!--          {{ getDisease(scope.row.diseaseId) }}-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSelect(scope.row)"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" :limit="1"/>
        </el-form-item>
        <el-form-item label="所属病种" prop="diseaseId">
          <el-select v-model="form.diseaseId" placeholder="请选择病种" style="width: 100%">
            <el-option
              v-for="item in diseaseOptions"
              :key="item.diseaseId"
              :label="item.illnessName"
              :value="item.diseaseId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open1" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" disabled/>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" disabled/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" :limit="1" disabled/>
        </el-form-item>
        <el-form-item label="所属病种" prop="diseaseId">
          <el-select v-model="form.diseaseId" placeholder="请选择病种" style="width: 100%" disabled>
            <el-option
              v-for="item in diseaseOptions"
              :key="item.diseaseId"
              :label="item.illnessName"
              :value="item.diseaseId"
              disabled
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listConsult, getConsult, delConsult, addConsult, updateConsult} from "@/api/counsult/consult"
import {getListDisease, getDisease} from "@/api/disease/disease"

export default {
  name: "Consult",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      open1: false,
      // 【请填写功能名称】表格数据
      consultList: [],
      diseaseOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        image: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'}
        ],
        image: [
          {required: true, message: '请上传图片', trigger: 'change'}
        ],
        diseaseId: [
          {required: true, message: '请选择病种', trigger: 'change'}
        ]
      }
    }
  },
  mounted() {
    getListDisease().then(response => {
      this.diseaseOptions = response.data
    })
  },
  created() {
    this.getList()
  },
  methods: {
    convertQuillHtmlToWxRichText(html) {
      if (!html) return html;

      const sizeMap = {
        small: '12px',
        normal: '16px',
        large: '24px',
        huge: '32px'
      };

      // 记录当前字体大小，初始为 undefined
      let currentFontSize = undefined;

      // 替换带 ql- 类的标签，顺便更新 currentFontSize
      html = html.replace(/<(\w+)([^>]*?)\sclass="([^"]*?ql-[^"]*?)"([^>]*?)>/gi, (match, tag, beforeAttrs, classNames, afterAttrs) => {
        const classes = classNames.split(/\s+/);
        const styles = [];
        const newClasses = [];

        classes.forEach(cls => {
          if (/ql-align-center/.test(cls)) {
            styles.push('text-align:center;');
          } else if (/ql-align-right/.test(cls)) {
            styles.push('text-align:right;');
          } else if (/ql-align-justify/.test(cls)) {
            styles.push('text-align:justify;');
          } else if (/ql-indent-(\d+)/.test(cls)) {
            const num = parseInt(RegExp.$1, 10);
            styles.push(`text-indent:${num * 2}em;`);
          } else if (/ql-size-(small|normal|large|huge)/.test(cls)) {
            const sizeKey = RegExp.$1;
            currentFontSize = sizeMap[sizeKey] || '16px';
            styles.push(`font-size:${currentFontSize} !important;`);
          } else if (/ql-color-([a-z0-9#]+)/.test(cls)) {
            const color = RegExp.$1;
            styles.push(`color:${color};`);
          } else if (/ql-bg-([a-z0-9#]+)/.test(cls)) {
            const bg = RegExp.$1;
            styles.push(`background-color:${bg};`);
          } else if (/ql-bold/.test(cls)) {
            styles.push('font-weight:bold;');
          } else if (/ql-italic/.test(cls)) {
            styles.push('font-style:italic;');
          } else if (/ql-underline/.test(cls)) {
            styles.push('text-decoration:underline;');
          } else if (/ql-strike/.test(cls)) {
            styles.push('text-decoration:line-through;');
          } else {
            newClasses.push(cls);
          }
        });

        const styleAttr = styles.length ? ` style="${styles.join('')}"` : '';
        const classAttr = newClasses.length ? ` class="${newClasses.join(' ')}"` : '';
        return `<${tag}${beforeAttrs}${classAttr}${styleAttr}${afterAttrs}>`;
      });

      // 列表转换
      html = html.replace(/<ul class="ql-list-bullet">/gi, '<ul>');
      html = html.replace(/<ol class="ql-list-ordered">/gi, '<ol>');
      html = html.replace(/class="ql-list-bullet"/gi, '');
      html = html.replace(/class="ql-list-ordered"/gi, '');

      // 移除残留 ql- 类
      html = html.replace(/\s?class="[^"]*?ql-[^"]*?"/gi, '');

      // 给内层 em,strong,span 标签强制加字体大小（用 currentFontSize 或默认16px）
      html = html.replace(/<(em|strong|span)([^>]*)>/gi, (match, tag, attrs) => {
        if (/style="[^"]*font-size:[^"]*"/i.test(attrs)) {
          // 已有字体大小，替换为带 !important
          return match.replace(/font-size:([^;"']+)/i, 'font-size:$1 !important');
        }
        const sizeToUse = currentFontSize || '16px';
        if (/style="/i.test(attrs)) {
          return `<${tag}${attrs.replace(/style="/, `style="font-size:${sizeToUse} !important; `)}>`;
        } else {
          return `<${tag}${attrs} style="font-size:${sizeToUse} !important;">`;
        }
      });

      return html;
    },
    getDisease(id) {
      getDisease(id).then(response => {
        return response.data.illnessName
      })
    },
    getDiseaseName(id) {
      const match = this.diseaseOptions.find(item => item.diseaseId === id);
      return match ? match.illnessName : '未知病种';
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listConsult(this.queryParams).then(response => {
        let rows = response.rows
        // 并行请求所有病种名
        let promises = rows.map(row => {
          return getDisease(row.diseaseId).then(res => {
            row.illnessName = res.data.illnessName
            return row
          })
        })
        Promise.all(promises).then(data => {
          this.consultList = data
          this.total = response.total
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.open1 = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        image: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加咨询"
    },
    convertFontSizeStyleToQuillClass(html) {
      return html
        .replace(/style="font-size:\s*32px\s*(!important)?\s*;?"/gi, 'class="ql-size-huge"')
        .replace(/style="font-size:\s*24px\s*(!important)?\s*;?"/gi, 'class="ql-size-large"')
        .replace(/style="font-size:\s*16px\s*(!important)?\s*;?"/gi, 'class="ql-size-normal"')
        .replace(/style="font-size:\s*12px\s*(!important)?\s*;?"/gi, 'class="ql-size-small"')
    },
    convertTabsToIndentStyle(html) {
      return html.replace(/<p>(\t+)(.*?)<\/p>/g, (match, tabs, text) => {
        const indentLevel = tabs.length; // tab 数量
        const indentEm = indentLevel * 2; // 每个tab对应2em缩进
        return `<p style="text-indent:${indentEm}em;">${text}</p>`;
      });
    },
    handleSelect(row) {
      this.reset()
      const id = row.id || this.ids
      getConsult(id).then(response => {
        this.form = response.data
        this.form.content = this.convertFontSizeStyleToQuillClass(this.form.content)
        console.log(this.form.content)
        this.open1 = true
        this.title = "查看咨询"
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getConsult(id).then(response => {
        this.form = response.data
        this.form.content = this.convertFontSizeStyleToQuillClass(this.form.content)
        this.open = true
        this.title = "修改咨询"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.content = this.form.content.replace(/<img\s+[^>]*src="([^"]+)"[^>]*>/g, function (match, p1) {
            return match.replace(/"/g, "'"); // 把 img 标签内的 " 全替换成 '
          });
          this.form.content = this.convertQuillHtmlToWxRichText(this.form.content)
          this.form.content = this.convertTabsToIndentStyle(this.form.content)
          console.log(this.form.content)
          if (this.form.id != null) {
            updateConsult(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addConsult(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除咨询编号为"' + ids + '"的数据项？').then(function () {
        return delConsult(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/consult/export', {
        ...this.queryParams
      }, `consult_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
